/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package canteen.sys.model.entity.repository;

import canteen.sys.SessionFactoryClass;
import canteen.sys.model.entity.LoginMaster;
import canteen.sys.model.generic.GenericHibernateDAOSupport;
import java.util.List;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;

/**
 *
 * @author TNT
 */
public class LoginDAOImpl extends GenericHibernateDAOSupport<LoginMaster, Long> implements LoginDAO {

    @Override
    public LoginMaster getUserByName(String userName) {

        Transaction transaction = getSession().beginTransaction();
        List<LoginMaster> users = getSession().createCriteria(LoginMaster.class)
                .add(Restrictions.eq("lName", userName)).list();
        transaction.commit();
        if (users.size() > 0) {
            return users.get(0);
        } else {
            return null;
        }
    }

    @Override
    public LoginMaster checkLogin(String userName, String password) {
        LoginMaster lm = new LoginMaster();
        LoginMaster user = getUserByName(userName);
        if (user != null) {
            if (user.getlPassword().equals(password)) {
                lm.setlId(user.getlId());
                lm.setlName(user.getlName());
                lm.setlPassword(user.getlPassword());
                lm.setlType(user.getlType());
            } else {
                throw new SecurityException("Password wrong!");
            }
        } else {
            throw new SecurityException("User name not exist!");
        }
        return lm;
    }
}
